package tool

import (
	"github.com/gin-gonic/gin"
	"github.com/kataras/iris/v12"
	"net/http"
	"reflect"
)

type ListRsp struct {
	List  interface{} `json:"list" comment:"列表数据"`
	Count int         `json:"count" comment:"总条数"`
}

type Rsp struct {
	Code int         `json:"code" comment:"状态码 0成功"`
	Msg  string      `json:"msg" comment:"失败信息"`
	Data interface{} `json:"data,omitempty" comment:"返回数据"`
}

func (r Rsp) GetMessage() string {
	return GetMsg(r.Code)
}

// 回复参数错误消息
func (r Rsp) ReplyInvalidParam(c interface{}) {
	r.Code = INVALID_PARAMS
	r.Msg = GetMsg(r.Code)
	replyJson(r, c)
}

// 回复成功， data为返回值
func (r Rsp) ReplySuccess(c interface{}, data interface{}) {
	r.Code = SUCCESS
	r.Msg = GetMsg(r.Code)
	r.Data = data
	replyJson(r, c)
}

// 回复成功， 自定义code
func (r Rsp) ReplySuccessCode(c interface{}, code int, data interface{}) {
	r.Code = code
	r.Data = data
	replyJson(r, c)
}

// 回复操作失败给前端，msg为失败原因
func (r Rsp) ReplyFailOperation(c interface{}, msg string) {
	r.Code = FAILE_TO_CREATE_OP
	r.Msg = msg
	replyJson(r, c)
}

// 回复自定义code 自定义消息
func (r Rsp) Reply(c interface{}, code int, msg string) {
	r.Code = code
	r.Msg = msg
	replyJson(r, c)
}
func replyJson(r Rsp, c interface{}) {
	switch app := c.(type) {
	case *gin.Context:
		app.Set("rsp", r)
		//判断是否是为空slice 为空slice时make
		if r.Code == SUCCESS {
			transfSlice(&r)
		}
		app.JSON(http.StatusOK, r)
	case iris.Context:
		app.Values().Set("rsp", r)
		if r.Code == SUCCESS {
			transfSlice(&r)
		}
		app.JSON(r)
	}

}
func transfSlice(r *Rsp) {
	v, ok := r.Data.(ListRsp)
	if ok {
		if reflect.TypeOf(v.List).Kind() == reflect.Slice && reflect.ValueOf(v.List).Len() == 0 {
			r.Data = ListRsp{List: make([]interface{}, 0), Count: v.Count}
		}
	} else {
		if reflect.TypeOf(r.Data).Kind() == reflect.Slice && reflect.ValueOf(r.Data).Len() == 0 {
			r.Data = make([]interface{}, 0)
		}
	}
}
